<template>
  <div class="upload_file">
    <el-upload
      ref="uploadFile"
      name="file"
      accept=".csv, .xlsx, .xls"
      :action="`${actionUrl}`"
      :show-file-list="false"
      :headers="myHeader"
      :file-list="fileList"
      :disabled="disabled"
      :data="uploadData"
      :auto-upload="autoUpload"
      :before-upload="beforeUpload"
      :on-change="changeFiles"
      :on-error="uploadError"
      :on-success="handleSuccess"
    >
      <slot />
    </el-upload>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { Loading } from 'element-ui'
export default {
  props: {
    btnText: {
      type: String,
      default: () => ''
    },
    action: {
      type: String,
      default: () => 'trafficfly-manager/api/goods/batchAddCornerMark'
    },
    autoUpload: {
      type: Boolean,
      default: () => true
    },
    disabled: {
      type: Boolean,
      default: () => false
    },
    uploadData: {
      type: Object,
      default: () => {}
    },
    submitUpload: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      Loading: null,
      fileList: []
    }
  },
  computed: {
    baseUrl() {
      return process.env.VUE_APP_BASE_API
    },
    myHeader() {
      return {
        authorization: getToken()
      }
    },
    actionUrl() {
      return this.baseUrl + this.action
    }
  },
  watch: {
    submitUpload(val) {
      if (val) {
        this.$refs.uploadFile.submit()
      }
    }
  },
  methods: {
    beforeUpload(file) {
      this.Loading = Loading.service({
        lock: true,
        text: '导入中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    uploadError() {
      this.$message({
        message: '导入失败',
        type: 'error'
      })
    },
    changeFiles(file, fileList) {
      this.$emit('update:submitUpload', false)
      this.$emit('onChange', file)
    },
    handleSuccess(res, data) {
      console.log(res, data)
      if (!res.body) {
        this.errMsg = res.heads.message || '上传失败'
        this.Loading.close()
        this.$message.error(this.errMsg)
        return false
      }
      this.$emit('result', res.body)
      this.Loading.close()
    }
  }
}
</script>
